#ifndef FRIENDS_H
#define FRIENDS_H

#include "postgresql/libpq-fe.h";
#include "table.h";
#include "iostream";
#include "time.h";

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>

using namespace std;

class Friends : public Table
{
	public:
		Friends ( ) : Table ( ) { }

		int Create( )
		{
			PGresult * res = PQexec( conn, "CREATE TABLE friends ( iduser1 integer, iduser2 integer, PRIMARY KEY ( iduser1, iduser2 ) );" );
			int result = PQresultStatus( res );
			if ( PQresultStatus( res ) == PGRES_COMMAND_OK )
				result = DB_OK;
			else
				result = DB_NO_RESULT;
			PQclear( res );
			return result;
		}

		int Clean( )
		{
			PGresult * res = PQexec( conn, "DROP TABLE friends;" );
			//			cout << PQresultStatus( res ) << endl;
			int result = PQresultStatus( res );
			if ( PQresultStatus( res ) == PGRES_COMMAND_OK )
				result = DB_OK;
			else
				result = DB_NO_RESULT;
			PQclear( res );
			return result;
		}

		int FindRecord( int iduser1, int iduser2, int & status ) // +
		{
			char st1[ 120 ] = "SELECT iduser1 FROM friends WHERE iduser1 = ";
			char st2[ 32 ];
			char st3[ 16 ] = " AND iduser2 = ";
			char st4[ 32 ];
			char st5[ 10 ] = " LIMIT 1;";

			sprintf( st2, "%i", iduser1 );
			sprintf( st4, "%i", iduser2 );
			strncat( st1, st2, 32 );
			strncat( st1, st3, 15 );
			strncat( st1, st4, 32 );
			strncat( st1, st5, 9 );

			PGresult * res = PQexec( conn, st1 );
			int result = PQresultStatus( res );
//			cout << "\t\t" << result << endl;
			if ( PQresultStatus( res ) == PGRES_TUPLES_OK )
			{
				if ( PQntuples( res ) )
				{
					result = DB_OK;
					char * endptr;
					status = 1;// strtol( PQgetvalue( res, 0, 0 ), &endptr, 10 ); // не проверяем.
				}
				else
				{
					result = DB_NO_RECORD;
					status = 0;
				}
			}
			else
			{
				result = DB_NO_RESULT;
				status = 0;
			}
//			cout << "idsession " << idsession << "\t" << result << endl;
			PQclear( res ); // ???
			return result;
		}

		int InsRecord( int iduser1, int iduser2 ) // +
		{
			int result;

			char st1[ 120 ] = "INSERT INTO friends (iduser1, iduser2) VALUES (";
			char st2[ 32 ];
			char st3[ 2 ] = ",";
			char st4[ 32 ];
			char st5[ 3 ] = ");";

			sprintf( st2, "%i", iduser1 );
			sprintf( st4, "%i", iduser2 );
			strncat( st1, st2, 32 );
			strncat( st1, st3, 1);
			strncat( st1, st4, 32);
			strncat( st1, st5, 2);


			PGresult * res = PQexec( conn, st1 );
//			cout << st1 << endl;
			if ( PQresultStatus( res ) == PGRES_COMMAND_OK )
				result = DB_OK;
			else
				result = DB_NO_RESULT;
			PQclear( res );

			return result;
		}

};

#endif // FRIENDS_H
